<template>
  <div>
    <a-table
      :row-selection="{
        selectedRowKeys: selectedRowKeys,
        onChange: onSelectChange,
      }"
      :columns="columns"
      :rowKey="(record) => record.id"
      :data-source="tableData"
      bordered
    >
      <template
        v-for="col in ['userName', 'email', 'phoneNumber']"
        #[col]="{ text, record }"
        :key="col"
      >
        <div>
          <a-input
            v-if="editableData[record.id]"
            v-model:value="editableData[record.id][col]"
            style="margin: -5px 0"
          />
          <template v-else>
            {{ text }}
          </template>
        </div>
      </template>
      <template #sex="{ record }">
        <span>
          <div v-if="editableData[record.id]">
            <a-radio-group v-model:value="editableData[record.id].sex">
              <a-radio :value="1">男</a-radio>
              <a-radio :value="2">女</a-radio>
            </a-radio-group>
          </div>
          <div v-else>
            <a-tag v-if="record.sex == 1">男</a-tag>
            <a-tag v-else>女</a-tag>
          </div>
        </span>
      </template>
      <template #operation="{ record }">
        <div class="editable-row-operations">
          <span v-if="editableData[record.id]">
            <a @click="save(record.id)" style="margin-right: 10px">Save</a>

            <a-popconfirm title="Sure to cancel?" @confirm="cancel(record.id)">
              <a>Cancel</a>
            </a-popconfirm>
          </span>
          <span v-else>
            <a @click="edit(record.id)" style="margin-right: 10px">Edit</a>
            <a-popconfirm
              v-if="dataSource.length"
              title="确定删除?"
              @confirm="onDelete(record.id)"
            >
              <a>Delete</a>
            </a-popconfirm>
          </span>
        </div>
      </template>
      <template #title>
        <!-- <a-button type="primary" class="distance" @click="showModal">
          <PlusSquareOutlined />
          添加
        </a-button> -->
        <adduser />
        <a-button
          type="danger"
          class="distance"
          :disabled="!hasSelected"
          :loading="loading"
          @click="mdelete()"
        >
          <DeleteOutlined />
          批量删除
        </a-button>
        搜索：
        <a-input-search
          v-model:value="search"
          placeholder="input search text"
          enter-button
        />
      </template>
    </a-table>
  </div>
</template>
<script>
  import { cloneDeep } from 'lodash-es'
  import { reactive, ref, computed, toRefs } from 'vue'
  import { getUserList } from '@/api/datatable.js'
  import { DeleteOutlined } from '@ant-design/icons-vue'
  import adduser from '@/components/form/adduser'
  export default {
    components: {
      DeleteOutlined,
      adduser,
    },
    setup() {
      const columns = [
        {
          title: '用户名',
          dataIndex: 'userName',
          width: '12%',
          slots: {
            customRender: 'userName',
          },
        },
        {
          title: '邮箱',
          dataIndex: 'email',
          width: '12%',
          slots: {
            customRender: 'email',
          },
        },
        {
          title: '手机号码',
          dataIndex: 'phoneNumber',
          width: '15%',
          slots: {
            customRender: 'phoneNumber',
          },
        },
        {
          title: '性别',
          dataIndex: 'sex',
          width: '5%',
          slots: {
            customRender: 'sex',
          },
        },

        {
          title: '创建时间',
          dataIndex: 'created',
          width: '20%',
          slots: {
            customRender: 'created',
          },
        },
        {
          title: '最后登录',
          dataIndex: 'lastLogin',
          width: '20%',
          slots: {
            customRender: 'lastLogin',
          },
        },
        {
          title: '角色',
          dataIndex: 'roleName',
          width: '10%',
          slots: {
            customRender: 'roleName',
          },
        },
        {
          title: 'operation',
          dataIndex: 'operation',
          slots: {
            customRender: 'operation',
          },
        },
      ]
      const data = []
      //表格数据
      const dataSource = ref(data)
      //编辑时存放的数据
      const editableData = reactive({})
      //数据接口绑定表格
      getUserList().then(function (res) {
        dataSource.value = res.data
      })
      //点击编辑，表格内编辑，放置editableData
      const edit = (id) => {
        editableData[id] = cloneDeep(
          dataSource.value.filter((item) => id === item.id)[0]
        )
      }
      //保存动作
      const save = (key) => {
        console.log(key)
        console.log(editableData[key])
        Object.assign(
          dataSource.value.filter((item) => key === item.id)[0],
          editableData[key]
        )
        // console.log(editableData[key])
        delete editableData[key]
      }
      //取消动作
      const cancel = (key) => {
        delete editableData[key]
      }

      let search = ref('')
      //搜索绑定表格
      const tableData = computed(() => {
        if (search.value) {
          return dataSource.value.filter((data) => {
            return Object.keys(data).some((key) => {
              return String(data[key]).toLowerCase().indexOf(search.value) > -1
            })
          })
        }
        return dataSource.value
      })
      const state = reactive({
        selectedRowKeys: [],
        // Check here to configure the default column
        loading: false,
      })
      const hasSelected = computed(() => state.selectedRowKeys.length > 0)
      const onSelectChange = (selectedRowKeys) => {
        console.log('selectedRowKeys changed: ', selectedRowKeys)
        state.selectedRowKeys = selectedRowKeys
      }
      const onDelete = (key) => {
        dataSource.value = dataSource.value.filter((item) => item.id !== key)
      }
      const mdelete = () => {
        console.log(state.selectedRowKeys)
        for (let i = 0; i < state.selectedRowKeys.length; i++) {
          // console.log(state.selectedRowKeys[i])
          onDelete(state.selectedRowKeys[i])
        }
      }
      return {
        dataSource,
        columns,
        editingKey: '',
        editableData,
        tableData,
        search,
        hasSelected,
        ...toRefs(state),
        edit,
        save,
        cancel,
        onSelectChange,
        onDelete,
        mdelete,
      }
    },
  }
</script>
<style scoped>
  .editable-row-operations a {
    margin-right: 8px;
  }
  .distance {
    margin-right: 20px;
  }
</style>
